// 引入axios以及element ui中的loading和message组件
import axios from "axios";
import router from "../router/index";
import { Message } from "element-ui";
import {
  showFullScreenLoading,
  tryHideFullScreenLoading,
} from "@/utils/loading";

// if (process.env.NODE_ENV !== 'development') {
//   axios.defaults.baseURL = process.env.VUE_APP_URL
// }

// http请求拦截器
axios.interceptors.request.use(
  (config) => {
    if (config.headers.isLoading !== false) {
      // 如果配置了isLoading: false，则不显示loading
      let info = "加载中";
      showFullScreenLoading(info);
    }
    config.headers["UserId"] = localStorage.getItem("userName");
    config.headers["Authorization"] = localStorage.getItem("token");

    let lang = " Chinese";
    config.headers["language"] = lang;
    return config;
  },
  (error) => {
    tryHideFullScreenLoading();
    Message.error({
      message: "加载超时",
    });
    return Promise.reject(error);
  }
);
// http响应拦截器
axios.interceptors.response.use(
  (data) => {
    // 响应成功关闭loading
    tryHideFullScreenLoading();
    if (data.data.code != 10001) {
      return data;
    } else {
      localStorage.clear();
      Message.error({
        message: data.data.message,
      });
      router.push({ path: "/login" });
      return;
    }
  },
  (error) => {
    Message.error({
      message: error.response.data.message
    });

    //当返回信息为未登录或者登录失效的时候重定向为登录页面
    // if (error.response.code == 10001) {
    //   Message.error({
    //     message: error.response.data.message
    //   });
    //   localStorage.clear();
    //   if (
    //     router.currentRoute.meta.requireAuth &&
    //     !localStorage.getItem("token")
    //   ) {
    //     router.push({
    //       path: "/login"
    //     });
    //     tryHideFullScreenLoading();
    //     return;
    //   }
    //   router.push({
    //     path: "/login",
    //     query: { redirect: router.currentRoute.fullPath } //从哪个页面跳转
    //   });
    // }
    tryHideFullScreenLoading();
    return Promise.reject(error);
  }
);

export { axios };
